local skynet = require "skynet"
require "skynet.manager"
local ServiceName = require "enum.ServiceName"
local Service = require "core.Service"

--[[
    mongodb 池，管理及绑定服务对应的具体 mongo 连接
]]
---@class MongoPool
local M = {}

---@type MongoAgent[]
local slaves = {}
local size = skynet.getenvn("mongo_pool_size")
local balance = 1

function M.start(conf)
    for i = 1, size do
        ---@type MongoAgent
        local s = Service:new(skynet.new_hotservice("service.MongoAgent"))
        s:start(conf)
        table.insert(slaves, s)
    end

    return true
end

-- 为服务绑定一个指定的 mongo 连接
function M.bind()
    assert(#slaves > 0, 'has not enough mongo agent')
    local s = slaves[balance]
    balance = balance + 1
    if balance > size then
        balance = 1
    end

    return s.address
end

function M.flush()
    for i = 1, #slaves do
        slaves[i]:flush()
    end
end

function M.flushCollection(collection)
    for i = 1, #slaves do
        slaves[i].flushCollection(collection)
    end
end

function M.dropCollection(collection)
    for i = 1, #slaves do
        slaves[i].dropCollection(collection)
    end
end

function M.init()
    skynet.dispatch_lua(M)
    skynet.register(ServiceName.MONGO_POOL)
end

return M
